package com.ir.slassm.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.Query;
import javax.jdo.PersistenceManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ir.slassm.vo.SLMessageVO;

public class SLMessageDAO {
	Log logger = LogFactory.getLog(SLMessageDAO.class.getName());
	
	@SuppressWarnings("unchecked")
	public List<SLMessageVO> findBySenderAndReciever(String senderId, String recieverId) {
		List<SLMessageVO> results = new ArrayList<SLMessageVO>();
		String sql = "senderId == senderIdParam && recieverId == recieverIdParam";
		
		Object[] params = new Object[] {senderId, recieverId};
		PersistenceManager pm = JDOFactory.getPersistanceManagerInstance(); 
		Query q = pm.newQuery(SLMessageVO.class, sql);
		q.declareParameters("String senderIdParam, String recieverIdParam");
		q.setOrdering("createdDate desc");
		
		try {
			results = (List<SLMessageVO>)pm.detachCopyAll((List<SLMessageVO>)q.executeWithArray(params));
		} finally {
			pm.close();
		}
		 
		return results;
	}
	
	public void save(SLMessageVO slMessage) throws Throwable {
		logger.info("save Enter.");
		PersistenceManager pm = JDOFactory.getPersistanceManagerInstance(); 
		try {
			pm.makePersistent(slMessage);
		} catch(Throwable t) {
			logger.warn("Failed to persist SLMessage: " + t.getMessage());
			throw t;
		} finally {
			pm.close();
		}
		logger.info("save Exit.");
	}
	
	public void delete(List<SLMessageVO> slMessageList) throws Throwable {
		logger.info("delete Enter.");
		
		PersistenceManager pm = JDOFactory.getPersistanceManagerInstance();
		try {
			pm.deletePersistentAll(slMessageList);
		} catch(Throwable t) {
			logger.error("Failed to delete all messages from the list.", t);
			throw t;
		} finally {
			pm.close();
		}
		logger.info("delete Exit.");
	}
	
	public void deleteByDataAgo(Date timeAgo) throws Throwable {
		logger.info("deleteByDataAgo Enter.");
		if(logger.isDebugEnabled()) {
			logger.debug("param timeAgo:" + timeAgo.toString());
		}
		PersistenceManager pm = JDOFactory.getPersistanceManagerInstance();
		Object[] params = new Object[] {timeAgo};
		String sql = "createdDate < createdDateParam";
		
		Query q = pm.newQuery(SLMessageVO.class, sql);
		q.declareImports("import java.util.Date");
		q.declareParameters("Date createdDateParam");
		try {
			q.deletePersistentAll(params);
		} catch(Throwable t) {
			throw t;
		} finally {
			pm.close();
		}
		logger.info("deleteByDataAgo Exit.");
	}
	
}
